#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MAXLINE 1024

int Create_socket(int port)
{
	int ret = 0;
	int sock_fd = -1;
	/*创建套接字*/
	sock_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == sock_fd)
	{
		printf("socket faild,err:%s\n", strerror(errno));
		return -1;
	}
	//设置端口复用
	int opt = 1;
	//setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,(const void *) &opt,sizeof(opt));
	/*绑定地址*/
	struct sockaddr_in sock_addr;
	sock_addr.sin_family = AF_INET;
	sock_addr.sin_port = htons(port);
	sock_addr.sin_addr.s_addr = INADDR_ANY;
	ret = bind(sock_fd, (struct sockaddr*)&sock_addr, sizeof(struct sockaddr_in));
	if(ret < 0)
	{
		printf("bind Error:%m\n");
		close(sock_fd);
		sock_fd = -1;
		return -1;
	}
	return sock_fd;
}

void str_cli(int sockfd)
{
	int maxfdp1,stdineof = 0;
	fd_set rset;
	char sendline[MAXLINE],recvline[MAXLINE];

	FD_ZERO(&rset);
	for( ; ; ){
		FD_SET(STDIN_FILENO,&rset);
		FD_SET(sockfd,&rset);
		maxfdp1 = (sockfd>STDIN_FILENO?sockfd:STDIN_FILENO) + 1;
		if(select(maxfdp1,&rset,NULL,NULL,NULL) < 0)
			printf("Error on select\n");

		if(FD_ISSET(STDIN_FILENO,&rset)){
			if(fgets(sendline,MAXLINE,stdin) == NULL){
				stdineof = 1;
				shutdown(sockfd,SHUT_WR);/*关闭写端*/
				FD_CLR(STDIN_FILENO,&rset);
				continue;
			}
			else{
				write(sockfd,sendline,MAXLINE);
				//shutdown(sockfd,SHUT_WR);/*关闭写端*/
			}
		}

		if(FD_ISSET(sockfd,&rset)){
			if(read(sockfd,recvline,MAXLINE) == 0){
				if(stdineof == 1){
					printf("sockfd EOF\n");
					return ;
				}
				else
					printf("str_cli : server terminated\n");
				return ;
			}
			printf(">%s",recvline);
		}

	}
}
/*
void str_cli(int sockfd)
{
	ssize_t n;
	char buf_w[1024],buf_r[1024];
again:
	while((n=read(0,buf_w,1024))>0)
	{
		write(sockfd,buf_w,n);
		read(sockfd,buf_r,1024);
		printf(">%s",buf_r);
		memset(buf_r,0,1024);
	}
	if(n<0 && errno == EINTR)
		goto again;
	else if(n < 0)
		printf("str_cli error:%m\n");
}
*/
int Do_Connect_socket(int sock_fd,char* srv_ip,int srv_port)
{
	//连接server端的ip和port
	struct sockaddr_in sock_server;
	sock_server.sin_port = htons(srv_port);
	sock_server.sin_addr.s_addr = inet_addr(srv_ip);
	sock_server.sin_family = PF_INET;
	memset(sock_server.sin_zero,0,8);
	int ret = connect(sock_fd,(struct sockaddr*)&sock_server,sizeof(struct sockaddr));
	if(-1 == ret)
	{
		close(sock_fd);
		printf(" connect faild,err:%s\n",strerror(errno));
		return -1;
	}

	return
		ret;
}

int main(void)
{
	int fd=0;
	int clilen;
	struct sockaddr_in srvaddr,cliaddr;
	fd=Create_socket(0);
	Do_Connect_socket(fd,"192.168.4.224",55560);
	str_cli(fd);	

	return 0;
}
